package com.cjh.common.service;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class UploadService {
    public String uploadFile(MultipartFile file,String pathPrefix){
        if (file.isEmpty()) {
            return " ";
        }
        // 文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀名
        String extension = fileName.substring(fileName.indexOf("."));
        // 上传文件的路径D://cloud_printing_upload/
        String uploadFolder = "D://cloud_printing_upload/"+pathPrefix;
        // 生成一个新的文件名
        fileName = UUID.randomUUID() + extension;

        File dest = new File(uploadFolder + fileName);
        // 检测文件目录是否存在 不存在则创建
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
//            System.out.println("上传文件成功！");
        } catch (IOException e) {
            e.printStackTrace();
//            System.out.println("上传文件失败！");
            return " ";
        }
        // 返回虚拟文件访问路径
        return "/upload/"+ pathPrefix + fileName;
    }

    public List<String> uploadMultiFile(MultipartFile[] files, String pathPrefix){
        List<String> list = new ArrayList<>();
        for (MultipartFile f : files){
            list.add(uploadFile(f,pathPrefix));
        }
        return list;
    }

    public String uploadOnlineFileToLocal(String fileUrl,String pathPrefix) {
        try {
            URL httpUrl = new URL(fileUrl);
            String fileName = UUID.randomUUID() + ".png";
            String uploadFolder = "D://cloud_printing_upload/"+pathPrefix;
            File dest = new File(uploadFolder + fileName);
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            FileUtils.copyURLToFile(httpUrl, dest);
            return "/upload/"+ pathPrefix + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
